const app = getApp();
var api = require('../../api.js');
var mta = require('../../mta_analysis.js');

Page({
  data: {
    judgeIos:true,
    settlementOn:false,
    show: false,
    show_attr_picker: false,
    judge:false,
    change: false,
    newmoney:0,
    use_integral:0,
    page:1,
    totalMoney:0,
    arr:[],
    anthologyArr:[]
  },
  onLoad: function (options) {
    var page = this ;
    app.bind();
    console.log(options);
    //let list = JSON.parse(options.str);
    page.setData({
      lesson_id: options.lessonId
    })
    console.log(page.data.lesson_id)
    page.getDetail();
    // this.settlementBtn();
    page.getOnlineDetail();
    page.getTotalMoney();

    wx.getNetworkType({
      success: function (res) {
        console.log(res)
        page.setData({
          networkType: res.networkType
        })
      }
    });

    mta.Page.init();
  },
  onReady: function () {

  },
  onShow: function () {
    var page = this;
    var equipmentSystem = wx.getStorageSync('equipmentSystem');
    console.log(equipmentSystem)
    page.setData({
      equipmentSystem: equipmentSystem
    })
    page.judgeIos();
  },
  onHide: function () {

    var url = app.getcurrentPageLessonId();
    wx.setStorageSync("from_url", url);

  },
  onUnload: function () {

  },
  onPullDownRefresh: function () {
    var that = this;
    // that.setData({
    //   page: that.data.count - 1
    // });
    // that.getDetail();

    // 显示顶部刷新图标  
    wx.showNavigationBarLoading();

    // 隐藏导航栏加载框  
    wx.hideNavigationBarLoading();

    //停止下拉刷新
    wx.stopPullDownRefresh();
  },
  onReachBottom: function () {
    var that = this;
    // 显示加载图标  
    wx.showLoading({
      title: '玩命加载中',
    });

    // if (that.data.page < that.data.count) {
      that.setData({
        page: that.data.page + 1
      });
    // }

    that.getDetail();
    // 隐藏加载框  
    wx.hideLoading();
  },
  onShareAppMessage: function () {
    var url = app.getcurrentPageLessonId();
    var user_id = wx.getStorageSync('user_id');
    return {
      path: url + "&user_id=" + user_id,
      title: '得道1314'
    };
  },

  //判断ios是否可以支付
  judgeIos: function () {
    var access_token = wx.getStorageSync('access_token');
    console.log(access_token)
    var page = this;
    wx.request({
      url: api.passport.is_ios,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token
      },

      success: function (res) {
        console.log(res);
        if (res.data.code == 1) {
          page.setData({
            judgeIos: false
          })
        }
      }


    });
  },

  //获取章节列表
  getDetail: function () {
    var that = this;
    var access_token = wx.getStorageSync('access_token');
    wx.request({
      url: api.index.lessonInfo,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        lesson_id: this.data.lesson_id,
        page:that.data.page
      },

      success: function (res) {
        console.log(res);
        if(res.data.code == 0){
          that.setData({
            title: res.data.data.info.name,
            list: res.data.data.list,
            image: res.data.data.info.image,
            info: res.data.data.info,
            is_buy: res.data.data.info.is_buy,
            row_count: res.data.data.row_count
          })
          console.log(that.data.info)
          console.log(that.data.row_count);
          Math.ceil(that.data.row_count / 10);
          that.setData({
            count: Math.ceil(that.data.row_count / 10)
          })
          console.log(that.data.count)
          wx.setNavigationBarTitle({
            title: that.data.title
          })

          if (that.data.page == 1) {
            that.getChoice()
          }

          for (var i = 0; i < that.data.list.length; i++) {

            that.data.list[i].num = i
          }

          that.setData({
            list: that.data.list
          })

          for (var i = 0; i < that.data.list.length; i++) {

            if (that.data.row_count == that.data.arr.length) {

            } else {
              that.data.arr.push(that.data.list[i]);
              that.setData({
                arr: that.data.arr
              })
            }

          }

          if (res.data.data.info.is_buy == true) {
            that.setData({
              judge: true,
              change: true,
            })
          }
        }else{
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        }
        
      }
    });
  },

  getInfoDetail: function () {
    var access_token = wx.getStorageSync('access_token');
    console.log(access_token)
    var that = this;
    wx.request({
      url: api.index.lessonInfo,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        lesson_id: that.data.lesson_id,
        page: that.data.allpage
      },

      success: function (res) {
        console.log(res);
        if (res.data.code == 0) {

          that.setData({
            allList: res.data.data.list
          })

          for (var i = 0; i < that.data.allList.length; i++) {
            var a = {};

            if (that.data.allList[i].is_free == 1) {
              a.title = '免费'
            } else {
              a.title = that.data.allList[i].stage
            }
            a.id = that.data.allList[i].id
            a.is_free = that.data.list[i].is_free;
            that.data.anthologyArr.push(a);
            that.setData({
              anthologyArr: that.data.anthologyArr
            })

          }
          console.log(that.data.anthologyArr)

          that.setData({
            changeId: that.data.anthologyArr[0].id
          })


        } else if (res.data.code == -1) {

        }
      }
    });
  },

  // 获取选节
  getChoice: function () {
    var page = this;
    for (var i = 0; i < page.data.count; i++) {
      console.log(i)
      var allpage = i + 1;
      console.log(allpage)
      page.setData({
        allpage: allpage
      })
      page.getInfoDetail()
    }

  },

  //跳转到详情
  toCourse:function(e){
    console.log(e);
    var page = this
    var index = e.currentTarget.dataset.index;

    var lesson_id = page.data.info.id
    var section_id = page.data.anthologyArr[index].id
    var is_free = page.data.anthologyArr[index].is_free

    if (this.data.is_buy == true){
      wx.navigateTo({
        url: '/pages/classDetail/classDetail?lesson_id=' + lesson_id + '&section_id=' + section_id,
      })
    }else{
      if (is_free == 1) {
        wx.navigateTo({
          url: '/pages/classDetail/classDetail?lesson_id=' + lesson_id + '&section_id=' + section_id,
        })
      } else {
        this.setData({
          show:true,
          tab_online: "active",
        });
        this.getTotalMoney();
      }
    }
      
      

    
  },

  // 跳转到详情
  toDetail: function (res) {
    var page = this
    console.log(res)
    var index = res.currentTarget.dataset.index
    console.log(index)
    var lesson_id = page.data.info.id
    var section_id = page.data.anthologyArr[index].id
    var proList = this.data.list;
    var is_free = page.data.anthologyArr[index].is_free;

    if (this.data.is_buy == true) {
      wx.navigateTo({
        url: '/pages/classDetail/classDetail?lesson_id=' + lesson_id + '&section_id=' + section_id,
      })
    } else {
      if(is_free == 1){
        wx.navigateTo({
          url: '/pages/classDetail/classDetail?lesson_id=' + lesson_id + '&section_id=' + section_id,
        })
      }else{
        this.setData({
          show: true,
          tab_online: "active",
        });
        this.getTotalMoney();
      }
        
      
    }
  },
  
  //tab页切换
  tab: function (e) {

    var tab = e.currentTarget.dataset.tab;

    if (tab == "online") {
      this.setData({
        tab_online: "active",
        show: true,
      });
      this.getTotalMoney();

    } else {
      
      
      
    }
  },

  //跳转到课程介绍
  toIntroduce:function(e){
    var proList = this.data.info;
    let str = JSON.stringify(proList);
    console.log(str)
    
    if (this.data.is_buy == false){
      wx.showToast({
        title: '请购买本专栏',
        icon: 'none',
      });
    }else{
      wx.navigateTo({
        url: '../../../../../pages/classIntroduce/classIntroduce?str=' + str,
      })
    }


    
  },


  //线上课提交前预览页面
  getOnlineDetail: function () {
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    wx.request({
      url: api.lessonOrder.submitPreview,
      method: "get",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.lesson_id,
      },

      success: function (res) {
        console.log(res);

        if (res.data.code == 0) {
          page.setData({
            lessonInfo: res.data.data.lesson_info,
            user: res.data.data.user,
            money: res.data.data.user.integral2money,
            integral: res.data.data.user.integral,
            price: res.data.data.lesson_info.price
          })
          console.log(page.data.integral)

        } else {
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        }

      }
    });
  },


  //线上开关选择器
  switchChange: function (e) {
    var page = this;
    console.log(e);
    page.setData({
      switchValue: e.detail.value
    })
    console.log(page.data.integral);

    if (page.data.switchValue == true) {
      page.setData({
        newmoney: page.data.money,
        use_integral: page.data.integral,
      })
    } else {
      page.setData({
        newmoney: 0,
        use_integral: 0
      })
    }
    page.getTotalMoney();
  },


  //线上获取总额
  getTotalMoney: function () {
    var page = this;
    var user_newmoney = page.data.newmoney;

    var price = page.data.price;
    console.log(user_newmoney)
    console.log(page.data.newmoney)
    var totalMoney = (parseFloat(price)*100 - parseFloat(user_newmoney)*100)/100
    page.setData({
      totalMoney: totalMoney
    })
  },

  //线上结算
  submitInfo: function (e) {
    console.log(e)
    var page = this;
    var access_token = wx.getStorageSync('access_token');
    console.log(page.data.use_integral)
    page.getTotalMoney();

    page.setData({
      settlementOn: true
    })
    
    wx.request({
      url: api.lessonOrder.submit,
      method: "post",
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        access_token: access_token,
        id: page.data.lesson_id,
        num: 1,
        use_integral: page.data.use_integral,
        form_id:e.detail.formId
      },

      success: function (res) {
        console.log(res);
        var data = res.data.data
        if (res.data.code == 0) {
          if (res.data.msg == "订单支付成功") {
            page.setData({
              judge: true,
              change: true,
            })
            page.getDetail();
          } else {
          //发起支付
          wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success: function (res) {
              console.log(res)
              page.setData({
                judge: true,
                change: true,
              })
              page.getDetail();
            },
            fail: function (res) {

            },
            complete: function (res) {

            },

          })
          }

        } else if (res.data.code == -1) {
          wx.navigateTo({
            url: '/pages/grant/grant',
          })
        }

      }
    });
  },

  //点击弹窗退出
  clear: function () {
    var page = this;
    page.setData({
      show: false,
      change: false,
    })
  },

  // 课程介绍
  toArticle: function (e) {
    var proList = this.data.info;
    let str = JSON.stringify(proList);
    
    wx.navigateTo({
      url: '/pages/classIntroduce/classIntroduce?str=' +str
    })
  },

  //跳转到首页
  toIndex: function () {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }
})